//
//  MLSComposeController.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/8/5.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit
import SVProgressHUD
private let toolBarHeight: CGFloat = 44
class MLSComposeController: UIViewController {
    // toolBar的约束(响应键盘的时候,更改约束,随键盘动)
    var toolBarBottomCons: NSLayoutConstraint?
    //MARK:- 表情键盘
    private lazy var emoticonKeyboard: EmoticonViewController = EmoticonViewController {[weak self](emoticon) -> () in
        self!.textView.insertEmoticon(emoticon)
    }
    //MARK:- tabBar表情按钮方法
    // 定义标记,表示更换键盘
    private var keyboardFlag = false
    func inputEmoticon() {
        // 退出响应
        textView.resignFirstResponder()
        // 更换键盘(nil为系统自带键盘)
        textView.inputView = keyboardFlag ? nil : emoticonKeyboard.keyboardView
        // 叫出键盘
        textView.becomeFirstResponder()
        // 修改标记(取反)
        keyboardFlag = !keyboardFlag
    }
    //MARK:- 系统方法
    // 布局控件
    override func loadView() {
        // 准备视图控件
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        // 准备导航栏
        prepareNavgationBar()
        prepareToolBar()
        prepareTextView()
        addKeyboardFrameChangeNoti()
    }
    // 设置键盘响应
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 让textView称为键盘第一响应者,叫出键盘
        textView.becomeFirstResponder()
    }
    //MARK:- 键盘处理
    func keyBoardShow(notif: NSNotification) {
        // 获取键盘显示后的frame
        let rect = notif.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 获取键盘动画时长
        let duriation = notif.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 更改toolBar的约束
        toolBarBottomCons?.constant = rect.origin.y - UIScreen.mainScreen().bounds.height
        // 设置toolBar的动画
        UIView.animateWithDuration(duriation, delay: 0, options: UIViewAnimationOptions(rawValue: 7<<16), animations: { () -> Void in
            // 强制更新约束
            self.view.layoutIfNeeded()
            }, completion: nil)
    }
    // 监听键盘通知
    private func addKeyboardFrameChangeNoti() {
        // 监听键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardShow:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    // 移除键盘通知
    private func removeKeyboardFrameChangeNoti() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK:- 准备文本输入框
    private func prepareTextView() {
        view.addSubview(textView)
        // 自动布局
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
        
        // 占位label
        textView.addSubview(placeHoderLabel)
        placeHoderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
    }
    // MARK:- 准备底部工具栏
    private func prepareToolBar() {
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        // 设置按钮
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            // 实例化item
            let item = UIBarButtonItem(nomalImageName: dict["imageName"], highLightedImageName: dict["imageName"]! + "_highlighted", target: self, action: dict["action"])
            items.append(item)
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 移除最后多的一个弹簧
        items.removeLast()
        toolBar.setItems(items, animated: true)
        
        // 布局toolBar
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: toolBarHeight))
        // 给toolBar的y值约束赋值
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    }
    
    //MARK:- 设置导航条
    private func prepareNavgationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendMessage")
        // 禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置顶部视图
        let topCenterView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 35))
        // 定义label
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 16)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleLabel.textAlignment = NSTextAlignment.Center
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 14)
        nameLabel.text = MLSAccessToken.shareAccessToken?.screen_name
        nameLabel.textAlignment = NSTextAlignment.Center
        nameLabel.sizeToFit()
        // 布局
        topCenterView.addSubview(titleLabel)
        topCenterView.addSubview(nameLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: topCenterView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: topCenterView, size: nil)
        
        navigationItem.titleView = topCenterView
    }
    //MARK:- 导航条按钮的方法
    func close() {
        // 关闭键盘
        textView.resignFirstResponder()
        // 关闭modal的控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK:-TODO 发布微博
    func sendMessage() {
        MLSNetworkTool.sharNewworkTools.sendStatus(textView.emoticonText) { (dict, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败！")
                self.dismissViewControllerAnimated(true, completion: nil)
            } else {
                SVProgressHUD.showSuccessWithStatus("发送成功！")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    //MARK:- 懒加载控件
    // 文本框占位label
    private lazy var placeHoderLabel: UILabel = {
        let label = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
        label.text = "分享新鲜事"
        label.sizeToFit()
        return label
    }()
    // 输入文字文本框
    private lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFontOfSize(18)
        // 允许拖拽
        textView.alwaysBounceVertical = true
        // 拖拽的时候,退出键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
        textView.backgroundColor = UIColor.whiteColor()
        // 设置代理
        textView.delegate = self
        return textView
    }()
    // 移除通知
    deinit {
        removeKeyboardFrameChangeNoti()
    }
    // 底部工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    
}
//MARK:- textView的代理方法
extension MLSComposeController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        // 更改提示占位label的文本隐藏属性,以及发送按钮的隐藏属性
        placeHoderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

